<template>
	<view id="wrapper">
		<!-- 地图底框 -->
		<div id="container"></div>
		<div id="panel"></div>
		<!-- 其他界面 -->
		<div id="addressInfo">
			<u--form labelPosition="left" id="addressForm">
				<u-form-item label="起点">
					<u--text type="success" :text="nowAddress"></u--text>
				</u-form-item>
				<u-form-item label="终点">
					<view :prop="endAddress" :change:prop="test.onEndAddressChange"></view>
					<u--input id="endAddressInput" v-model="endAddress" disabledColor="#ffffff" placeholder="请输入终点"
						:prop="endAddress" :change:prop="test.onChange" border="bottom"></u--input>
				</u-form-item>
			</u--form>
			<div id="btn-group">
				<button type="primary" @tap="test.searchPlace" style="width: 80%;" size="mini">查找终点</button>
			</div>
			<u-modal :show="showModal" :title="title" :showConfirmButton="showConfirmButton"
				:showCancelButton="showCancelButton" @cancel="cancelModal" @confirm="confirmModal">
				<view class="slot-content">
					<rich-text :nodes="content"></rich-text>
				</view>
			</u-modal>
		</div>
		<view :prop="nowLocation" :change:prop="test.onNowLocationChange"></view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				nowAddress: '',
				endAddress: '',
				nowLocation: [],
				showModal: false,
				title: '确认地点',
				content: ``,
				showConfirmButton: true,
				showCancelButton: true,
				endLocation: {}
			}
		},
		mounted() {
			this.getLocation()
		},
		methods: {
			//获取经纬度
			getLocation() {
				uni.getLocation({
					type: 'gcj02', //返回可以用于uni.openLocation的经纬度
					success: (res) => {
						let locationArr = []
						locationArr[0] = res.longitude
						locationArr[1] = res.latitude
						this.nowLocation = locationArr
					},
					fail: function(resp) {
						console.log(resp);
					}
				});
			},
			recevicePlaceSearchResult(data) {
				this.content = data.content;
				this.showModal = data.showModal
				this.endLocation = data.endLocation
			},
			receiveNowAddress(data) {
				this.nowAddress = data.nowAddress
			},
			cancelModal() {
				this.showModal = false;
			},
			confirmModal() {
				uni.setStorageSync('data', {
					endLocation: this.endLocation,
					startLocation: this.nowLocation
				})
				uni.switchTab({
					url: '/pages/run/run',
				})
			}
		}
	}
</script>

<script module="test" lang="renderjs">
	import AMapLoader from "@amap/amap-jsapi-loader";

	export default {
		name: "main",
		data() {
			return {
				map: '',
				placeSearch: '',
				nowLocation: [],
				endAddress: '',

				// 记录父级
				ownerInstance: null,
			};
		},
		unmounted() {
			this.map?.destroy();
		},
		methods: {
			// 当service层中的endAddress值改变时调用
			onEndAddressChange(newValue, oldValue, ownerInstance, instance) {
				this.endAddress = newValue
			},
			// 当service层中的nowLocation值改变时调用
			onNowLocationChange(newValue, oldValue, ownerInstance, instance) {
				this.nowLocation = newValue
				this.ownerInstance = ownerInstance
				this.initAMap();
			},
			initAMap() {
				window._AMapSecurityConfig = {
					securityJsCode: "94697b54d35ad233d46a0364900a86c9",
				};
				AMapLoader.load({
						key: "bd1509b2c8644f4eb8ac504fbf4db856", // 申请好的Web端开发者Key，首次调用 load 时必填
						version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
						plugins: ["AMap.Scale",
							"AMap.PlaceSearch",
							"AMap.AutoComplete",
							"AMap.Geocoder"
						], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
					})
					.then((AMap) => {
						this.map = new AMap.Map("container", {
							// 设置地图容器id
							viewMode: "3D", // 是否为3D地图模式
							center: this.nowLocation, // 初始化地图中心点位置
							zoom: 17, // 初始化地图级别
						});
						let that = this;

						// JS版本API 逆向查询 根据经纬度反查询出初始地址
						AMap.plugin('AMap.Geocoder', function() {
							var geocoder = new AMap.Geocoder()
							var lnglat = that.nowLocation

							geocoder.getAddress(lnglat, function(status, result) {
								if (status === 'complete' && result.info === 'OK') {
									// result为对应的地理位置详细信息
									that.ownerInstance.callMethod('receiveNowAddress', {
										nowAddress: result.regeocode.formattedAddress
									})
								}
							})
						})

						// 地点搜索
						AMap.plugin(["AMap.PlaceSearch"], function() {
							that.placeSearch = new AMap.PlaceSearch({
								pageSize: 5, //单页显示结果条数
								pageIndex: 1, //页码
								map: that.map, //展现结果的地图实例
								panel: "panel", //参数值为你页面定义容器的 id 值<div id="my-panel"></div>，结果列表将在此容器中进行展示。
								autoFitView: true, //是否自动调整地图视野使绘制的 Marker 点都处于视口的可见范围
							})
						});
					})
					.catch((e) => {
						console.log(e);
					});
			},

			// 地点搜索
			searchPlace(e, ownerInstance) {
				this.placeSearch.search(this.endAddress, function(status, result) {
					//查询成功时，result 即对应匹配的 POI 信息 父子通信返回给service层
					let doms = document.querySelectorAll('.poibox')
					for (let i = 0; i < doms.length; i++) {
						const index = doms[i].getAttribute('data-idx');
						doms[i].addEventListener("click", function() {
							let endLocation = result.poiList.pois[index].location
							let addressName = result.poiList.pois[index].name
							ownerInstance.callMethod('recevicePlaceSearchResult', {
								endLocation: endLocation,
								showModal: true,
								content: `确定要以${addressName}为终点吗？`
							})
						})
					}
				})
			},
		},
	}
</script>

<style scoped>
	uni-page-body {
		height: 100%;
	}

	#wrapper {
		width: 100%;
		height: 100%;
		position: relative;
	}

	#container {
		width: 100%;
		height: 800px;
	}

	#panel {
		position: fixed;
		background-color: white;
		max-height: 30%;
		overflow-y: scroll;
		bottom: 10px;
		width: 100%;
	}

	#addressInfo {
		position: absolute;
		width: 100%;
		height: 200px;
		z-index: 99;
		top: 0;
		border-radius: 0px 0px 5% 5%;
		background-color: white;
	}

	#addressForm {
		width: 80%;
		margin: 0 auto;
		padding: 0;
		margin-top: 5%;
	}

	#btn-group {
		margin-top: 2%;
		width: 100%;
		display: flex;
	}
</style>